package org.vaadin.example.biz.impl;

import cn.hutool.core.collection.CollUtil;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.vaadin.example.orm.entity.SysAccount;
import org.vaadin.example.orm.entity.table.AccountRoleTableDef;
//import org.vaadin.example.orm.entity.table.AccountTableDef;
import org.vaadin.example.orm.entity.table.SysAccountTableDef;
import org.vaadin.example.orm.mapper.AccRoleMapper;
import org.vaadin.example.orm.mapper.AccountMapper;
import org.vaadin.example.orm.mapper.SRoleMapper;
import org.vaadin.example.orm.entity.AccountRole;
import org.vaadin.example.orm.entity.SRole;
//import org.vaadin.example.model.entity.table.AccountRoleTableDef;
//import org.vaadin.example.model.entity.table.AccountTableDef;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserQueryService {

    @Autowired
    private AccRoleMapper accRoleMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private SRoleMapper sRoleMapper;

    public List<SRole> getUserRoles(String username) {
        SysAccount sysAccount = accountMapper.selectOneByQuery(
                QueryWrapper.create().select().where(SysAccountTableDef.SYS_ACCOUNT.USER_NAME.eq(username))
        );
        if (sysAccount != null) {
            List<AccountRole> accountRoles = accRoleMapper.selectListByQuery(
                    QueryWrapper.create().select().where(AccountRoleTableDef.ACCOUNT_ROLE.ACCOUNT_ID.eq(sysAccount.getId()))
            );
            if (CollUtil.isNotEmpty(accountRoles)) {
                return sRoleMapper.selectListByIds(accountRoles.stream().map(AccountRole::getRoleId).collect(Collectors.toList()));
            }
        }
        return new ArrayList<>();
    }

}
